package com.github.prontera.config;

import java.util.ArrayList;
import java.util.List;

import com.github.prontera.domain.Client;

/**
 * 构建树形结构
 */
public class NodeTreeBuilder {

	private List<Client> nodes = new ArrayList<Client>();

	public NodeTreeBuilder(List<Client> nodes) {
		this.nodes = nodes;
	}

	/**
	 * 构建树形结构
	 */
	public List<Node> buildTree() {
		List<Node> treeNodes = new ArrayList<Node>();
		List<Node> rootNodes = getRootNodes();
		for (Node rootNode : rootNodes) {
			buildChildNodes(rootNode);
			treeNodes.add(rootNode);
		}
		return treeNodes;
	}

	/**
	 * 递归子节点
	 */
	public void buildChildNodes(Node node) {
		List<Node> children = getChildNodes(node);
		if (!children.isEmpty()) {
			for (Node child : children) {
				buildChildNodes(child);
			}
			node.setNodes(children);
		}
	}

	/**
	 * 获取父节点下所有的子节点
	 */
	public List<Node> getChildNodes(Node pnode) {
		List<Node> childNodes = new ArrayList<Node>();
		for (Client n : nodes) {
			if (n.getInvitationClientId()!=null&&n.getInvitationClientId().longValue()==pnode.getId()) {
				Node node=new Node();
				node.setId(n.getId());
				node.setPid(n.getInvitationClientId());
				node.setText(n.getNickname());
				childNodes.add(node);
			}
		}
		return childNodes;
	}

	/**
	 * 判断是否为根节点
	 */
	public boolean rootNode(Client node) {
		boolean isRootNode = true;
		for (Client n : nodes) {
			if (node.getInvitationClientId()!=null&&node.getInvitationClientId().longValue()==n.getId()) {
				isRootNode = false;
				break;
			}
		}
		return isRootNode;
	}

	/**
	 * 获取集合中所有的根节点
	 */
	public List<Node> getRootNodes() {
		List<Node> rootNodes = new ArrayList<Node>();
		for (Client n : nodes) {
			if (rootNode(n)) {
				Node node=new Node();
				node.setId(n.getId());
				node.setPid(n.getInvitationClientId());
				node.setText(n.getNickname());
				rootNodes.add(node);
			}
		}
		return rootNodes;
	}

	public static class Node {

		private Long id;
		private Long pid;
		private String text;
		private String url;
		private List<Node> nodes;

		public Node() {
		}

		public Node(Long id, Long pid, String text, String url) {
			this.id = id;
			this.pid = pid;
			this.text = text;
			this.url = url;
		}

		public Long getId() {
			return id;
		}

		public void setId(Long id) {
			this.id = id;
		}

		public Long getPid() {
			return pid;
		}

		public void setPid(Long pid) {
			this.pid = pid;
		}

		public String getText() {
			return text;
		}

		public void setText(String text) {
			this.text = text;
		}

		public String getUrl() {
			return url;
		}

		public void setUrl(String url) {
			this.url = url;
		}

		public List<Node> getNodes() {
			return nodes;
		}

		public void setNodes(List<Node> menus) {
			this.nodes = menus;
		}

	}

}